<?php

class Application_Model_BlockMapper
{
    protected $_dbTable;

    private static $_blocks = null;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Block');
        }
        return $this->_dbTable;
    }

    public function findAll()
    {

        $language = Zend_Registry::get('language');
        $db       = Zend_Registry::get('db');
        $return   = array();

        if ($db && $language->getId() > 0) {
            $select = $db->select()->from(array('b' => 'block'));
            $select->join(array('bl' => 'block_local'), 'bl.block_id = b.id');
            $select->where('bl.language_id = ?', $language->getId());
            $stmt    = $db->query($select);
            $results = $stmt->fetchAll();

            if (!empty($results) && is_array($results))
            {
                foreach ($results as $result)
                {
                    if (!empty($result) && is_array($result))
                    {
                        $model = new Application_Model_Block();
                        if (!empty($result['id']))
                        {
                            $model->setId($result['id']);
                        }
                        if (!empty($result['key']))
                        {
                            $model->setKey($result['key']);
                        }
                        if (!empty($result['content']))
                        {
                            $model->setContent($result['content']);
                        }
                        $return[$model->getKey()] = $model;
                    }
                }
            }
        }

        return $return;
    }

    public function findByKey($key)
    {
        if (self::$_blocks == null)
        {
            self::$_blocks = $this->findAll();
        }
        if (!empty(self::$_blocks[$key]))
        {
            return self::$_blocks[$key];
        }
        return false;
    }

}